package com.example.springboot_demo.demos.web.websocket_work.Service;


import com.example.springboot_demo.demos.web.websocket_work.Websocket.WebSocketServer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;
import javax.websocket.Session;
import java.io.IOException;

@Component
public class MessageBroadcaster implements MessageListener {
    private static final String CHANNEL = "chat_channel";
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 发送消息到频道
        public void broadcast(String message) {
        redisTemplate.convertAndSend(CHANNEL, message);
    }

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String msg = redisTemplate.getStringSerializer().deserialize(message.getBody());
        for (Session session : WebSocketServer.chatSessionMap.get(WebSocketServer.key).values()) {
            try {
                session.getBasicRemote().sendText(WebSocketServer.mapper.readTree(msg).asText());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("广播消息内容：" + msg);
    }
}
